package com.sgcc.cy.util;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * json转换类
 */
public class JsonConvert {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonConvert.class);

    /**
     * json 转换为 对象
     *
     * @param json json串
     * @param cl   类型
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static <T> T jsonToObject(String json, Class<T> cl) {
        try {
            return MAPPER.readValue(json.getBytes(StandardCharsets.UTF_8), cl);
        } catch (JsonParseException e) {
            LOGGER.error("JsonParseException", e);
        } catch (JsonMappingException e) {
            LOGGER.error("JsonMappingException", e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("UnsupportedEncodingException", e);
        } catch (IOException e) {
            LOGGER.error("IOException", e);
        }
        return null;
    }

    public static <T> T jsonToObject(String json, TypeReference<T> cl) {
        try {
            return MAPPER.readValue(json, cl);
        } catch (Exception e) {
            LOGGER.error("jsonToObject1 occur Exception", e);
        }
        return null;
    }

    /**
     * 对象转换为json
     *
     * @param obj 需要转换对象
     * @return 转换后的json串
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String objectToJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonGenerationException e) {
            LOGGER.error("JsonGenerationException", e);
        } catch (JsonMappingException e) {
            LOGGER.error("JsonMappingException", e);
        } catch (IOException e) {
            LOGGER.error("IOException", e);
        }
        return null;
    }
}
